<template>
  <div id="part-admin">
    <!-- 第一部分，搜索栏 -->
    <div class="block1 block">
      <div class="block1-quick">
        <!-- 快捷查询 -->
        <el-form :label-width="150" v-if="isQuickSearch" :model="reqBody">
          <el-form-item class="form-item" label="规则ID">
            <el-input v-model="reqBody.rule_id" placeholder="规则ID"></el-input>
          </el-form-item>
          <el-form-item class="form-item">
            <el-button class="form-btn" @click="searchByRuleId" type="primary"
              ><el-icon><Search /></el-icon>&nbsp;直接查询</el-button
            >
            <el-button class="form-btn" @click="isQuickSearch = false"
              ><el-icon><Aim /></el-icon>改为定位</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 详细查询 -->
        <el-form :inline="true" :label-width="150" v-else>
          <!-- 规则ID -->
          <el-form-item class="form-item" label="规则Id">
            <el-input
              v-model="reqBody.rule_id"
              placeholder="rule_id"
            ></el-input>
          </el-form-item>
          <!-- 描述 -->
          <el-form-item class="form-item" label="描述">
            <el-input
              v-model="reqBody.description"
              placeholder="description"
            ></el-input>
          </el-form-item>
          <!-- 依据 -->
          <el-form-item class="form-item" label="依据">
            <el-input v-model="reqBody.info" placeholder="info"></el-input>
          </el-form-item>
          <!-- 备注 -->
          <el-form-item class="form-item" label="备注">
            <el-input v-model="reqBody.note" placeholder="note"></el-input>
          </el-form-item>
          <!-- 是否有效 -->
          <el-form-item class="form-item" label="是否有效">
            <el-select v-model="reqBody.isValid" placeholder="isValid">
              <el-option label="不限" :value="null"></el-option>
              <el-option label="是" :value="true"></el-option>
              <el-option label="否" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <!-- 算子名称 -->
          <el-form-item class="form-item" label="算子名称">
            <el-input v-model="reqBody.field" placeholder="field"></el-input>
          </el-form-item>
          <!-- 算子操作符 -->
          <el-form-item class="form-item" label="算子操作符">
            <el-input
              v-model="reqBody.operator"
              placeholder="operator"
            ></el-input>
          </el-form-item>
          <!-- of -->
          <el-form-item class="form-item" label="of">
            <el-input v-model="reqBody.of" placeholder="of"></el-input>
          </el-form-item>
          <!-- by -->
          <el-form-item class="form-item" label="by">
            <el-input v-model="reqBody.by" placeholder="by"></el-input>
          </el-form-item>
          <!-- than（字符） -->
          <el-form-item class="form-item" label="than">
            <el-input v-model="reqBody.than" placeholder="than"></el-input>
          </el-form-item>
          <!-- in_one_（字符） -->
          <el-form-item class="form-item" label="in_one_">
            <el-input
              v-model="reqBody.in_one_"
              placeholder="in_one_"
            ></el-input>
          </el-form-item>
          <!-- price_lt（数字） -->
          <el-form-item class="form-item" label="price_lt">
            <el-input
              v-model.number="reqBody.price_lt"
              placeholder="price_lt"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- time_gte（数字） -->
          <el-form-item class="form-item" label="time_gte">
            <el-input
              v-model.number="reqBody.time_gte"
              placeholder="time_gte"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- time_lte（数字） -->
          <el-form-item class="form-item" label="time_lte">
            <el-input
              v-model.number="reqBody.time_lte"
              placeholder="time_lte"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- plus（数字） -->
          <el-form-item class="form-item" label="plus">
            <el-input
              v-model.number="reqBody.plus"
              placeholder="plus"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- plus_unit（字符） -->
          <el-form-item class="form-item" label="plus_unit">
            <el-input
              v-model="reqBody.plus_unit"
              placeholder="plus_unit"
            ></el-input>
          </el-form-item>
          <!-- plus_before_times（数字） -->
          <el-form-item class="form-item" label="plus_before_times">
            <el-input
              v-model.number="reqBody.plus_before_times"
              placeholder="plus_before_times"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- times（数字） -->
          <el-form-item class="form-item" label="times">
            <el-input
              v-model.number="reqBody.times"
              placeholder="times"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- plus_after_times（数字） -->
          <el-form-item class="form-item" label="plus_after_times">
            <el-input
              v-model.number="reqBody.plus_after_times"
              placeholder="plus_after_times"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- time_span（数字） -->
          <el-form-item class="form-item" label="time_span">
            <el-input
              v-model.number="reqBody.time_span"
              placeholder="time_span"
              type="number"
            ></el-input>
          </el-form-item>
          <!-- time_unit（字符） -->
          <el-form-item class="form-item" label="time_unit">
            <el-input
              v-model="reqBody.time_unit"
              placeholder="time_unit"
            ></el-input>
          </el-form-item>
          <!-- itemextra（字符） -->
          <el-form-item class="form-item" label="itemextra">
            <el-input
              v-model="reqBody.itemextra"
              placeholder="itemextra"
            ></el-input>
          </el-form-item>
          <!-- itemscene（字符） -->
          <el-form-item class="form-item" label="itemscene">
            <el-input
              v-model="reqBody.itemscene"
              placeholder="itemscene"
            ></el-input>
          </el-form-item>
          <!-- 按钮组 -->
          <el-form-item class="form-item inline-form-btn">
            <el-button class="form-btn" @click="locate" type="primary"
              ><el-icon><Search /></el-icon>&nbsp;定位查询</el-button
            >
            <el-button class="form-btn" @click="isQuickSearch = true"
              ><el-icon><Promotion /></el-icon>改为直接</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 第一部分，搜索栏 END -->
    <!-- 第二部分整体 -->
    <div class="block2and3 block">
      <!-- 第二部分 规则信息 -->
      <div class="block2" id="block2-info">
        <el-scrollbar>
          <!-- BLOCK2-INFO -->
          <el-form
            label-width="100px"
            v-if="ruleFlatDatum && block2Content === 'info'"
          >
            <el-form-item label="规则ID">
              <el-input
                v-model="ruleFlatDatum.ruleId"
                placeholder="规则ID"
              ></el-input>
            </el-form-item>
            <el-form-item label="标识">
              <el-input
                v-model.number="ruleFlatDatum.mark"
                placeholder="标识"
              ></el-input>
            </el-form-item>
            <el-form-item label="序号">
              <el-input
                v-model.number="ruleFlatDatum.ord"
                placeholder="序号"
              ></el-input>
            </el-form-item>
            <el-form-item label="科室">
              <el-input
                v-model="ruleFlatDatum.dept"
                placeholder="科室"
              ></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="ruleFlatDatum.description"
                type="textarea"
                placeholder="描述"
                :rows="3"
              ></el-input>
            </el-form-item>
            <el-form-item label="条件">
              <el-input
                v-model="ruleFlatDatum.condition"
                type="textarea"
                placeholder="条件"
                :rows="3"
              ></el-input>
            </el-form-item>
            <el-form-item label="依据">
              <el-input
                v-model="ruleFlatDatum.info"
                type="textarea"
                placeholder="依据"
                :rows="3"
              ></el-input>
            </el-form-item>
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="ruleFlatDatum.beginDate"
                type="date"
                placeholder="选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="ruleFlatDatum.endDate"
                type="date"
                placeholder="选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="是否有效">
              <el-select v-model="ruleFlatDatum.isValid" placeholder="请选择">
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <!-- BLOCK2-INFO END -->
          <!-- BLOCK2-APPLY -->
          <div id="block2-apply" v-else-if="block2Content === 'apply'">
            <rule-apply :applyData="applyData" />
          </div>
          <!-- BLOCK2-APPLY END -->
          <!-- BLOCK2-SQLSTR -->
          <div id="block2-sqlstr" v-else-if="block2Content === 'sqlstr'">
            <rule-sql-str :sql-data="sqlData" />
          </div>
          <!-- BLOCK2-SQLSTR END -->
          <!-- BLOCK2-SQL END -->
          <div id="block2-sql" v-else-if="block2Content === 'sql'">
            <rule-sql :sql-data="sqlData" />
          </div>
        </el-scrollbar>
      </div>
      <!-- 第二部分 规则信息 END -->
      <!-- 第三部分 规则JSON编辑器 -->
      <div class="block3">
        <el-scrollbar>
          <div class="block3-prebox" v-if="ruleFlatDatum">
            <div class="block3-btnbox">
              <el-button @click="saveAllChanges" type="primary"
                ><el-icon><SuccessFilled /></el-icon>保存</el-button
              >
              <el-button @click="resetAllChanges" type="warning"
                ><el-icon><CircleCloseFilled /></el-icon>还原</el-button
              >
              <el-button @click="showLogDialog" type="info"
                ><el-icon><InfoFilled /></el-icon>日志</el-button
              >
              <el-button
                :type="block2Content === 'info' ? 'success' : 'info'"
                @click="block2Content = 'info'"
              >
                <el-icon><DataBoard /></el-icon>INFO
              </el-button>
              <el-button
                :type="block2Content === 'apply' ? 'success' : 'info'"
                @click="block2Content = 'apply'"
              >
                <el-icon><DataLine /></el-icon>APPLY
              </el-button>
              <el-button
                :type="block2Content === 'sqlstr' ? 'success' : 'info'"
                @click="block2Content = 'sqlstr'"
              >
                <el-icon><Document /></el-icon>SQLSTR
              </el-button>
              <el-button
                :type="block2Content === 'sql' ? 'success' : 'info'"
                @click="block2Content = 'sql'"
              >
                <el-icon><TrendCharts /></el-icon>SQL
              </el-button>
              <el-select
                v-model="focusHsp"
                placeholder="关注医院"
                style="margin-left: 15px; width: 50px"
              >
                <el-option
                  v-for="hsp in hspAbbrList"
                  :key="hsp"
                  :label="hsp"
                  :value="hsp"
                ></el-option>
              </el-select>
            </div>
            <json-editor-vue v-model="ruleFlatDatum" :options="editorOptions" />
          </div>
          <div v-else class="no-data">
            <p>请先查询数据</p>
          </div>
        </el-scrollbar>
      </div>
      <!-- 第三部分 规则JSON编辑器 END -->
    </div>
    <!-- 第二三部分整体 END -->
    <!-- 弹窗ruleLocate -->
    <el-dialog title="定位查询" v-model="isLocateDialogVisible">
      <rule-locate :rules="ruleMenu" @locate-selected="handleLocateSelected" />
    </el-dialog>
    <!-- 弹窗ruleLocate END -->
    <!-- 弹窗ruleLog -->
    <el-dialog title="日志" v-model="isLogDialogVisible" width="60%" :close-on-press-escape="false">
      <rule-log
        :log-list="ruleFlatDatum?.logList || []"
        @update:logList="handleUpdateLogList"
      />
    </el-dialog>
    <!-- 弹窗ruleLog END -->
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
// 载入 axios
import axios from "axios";
// 导入 Element Plus 消息组件
import { ElMessage } from "element-plus";
import JsonEditorVue from "json-editor-vue3";

// 定义 block2Content，默认显示 info
const block2Content = ref("info");

// 定义查询传入体
const reqBody = ref({
  rule_id: null,
  ruleId: null,
  description: null,
  info: null,
  note: null,
  isValid: null,
  field: null,
  operator: null,
  of: null,
  by: null,
  than: null,
  in_one_: null,
  price_lt: null,
  time_gte: null,
  time_lte: null,
  plus: null,
  plus_unit: null,
  plus_before_times: null,
  times: null,
  plus_after_times: null,
  time_span: null,
  time_unit: null,
  itemextra: null,
  itemscene: null,
});

// 监听 reqBody.rule_id 的变化，赋值给 reqBody.ruleId
watch(
  () => reqBody.value.rule_id,
  (newVal) => {
    reqBody.value.ruleId = newVal;
  }
);

// 定义展开过程
const isQuickSearch = ref(true);

// 监听 ruleFlatData 的变化，如果至少有一个元素，则 ruleFlatDatumOrigin.value = ruleFlatData.value[0]
const ruleFlatData = ref([]);
const ruleFlatDatumOrigin = ref(null);
const ruleFlatDatum = ref(null);
watch(
  () => ruleFlatData.value,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      ruleFlatDatumOrigin.value = newVal[0];
      ruleFlatDatum.value = JSON.parse(JSON.stringify(newVal[0])); // 深拷贝，防止引用问题
      console.log("设置 ruleFlatDatum:", ruleFlatDatum.value);
    } else {
      ruleFlatDatumOrigin.value = null;
      ruleFlatDatum.value = null;
    }
  }
);

// 定义直接查询事件
const searchByRuleId = () => {
  // 调用后端接口：/api/rule_flatten/query/json，用post
  axios
    .post("/api/rule_flatten/query/json", reqBody.value)
    .then((response) => {
      if (response.data.mark == "OK") {
        ruleFlatData.value = response.data.data;
      } else {
        alert("查询失败：" + response.data.msg);
        console.error("searchByRuleId, 查询失败：", response.data);
      }
    })
    .catch((error) => {
      alert("查询失败：", error);
      console.error("searchByRuleId, 查询失败：", error);
    });
};

// 保存所有修改
const saveAllChanges = () => {
  if (!ruleFlatDatum.value) {
    ElMessage.warning("没有可保存的数据");
    return;
  }

  // 调用后端接口：/api/rule_flatten/upload/by_rule_id/json，用post，用 "data": ruleFlatDatum.value
  axios
    .post("/api/rule_flatten/upload/by_rule_id/json", {
      data: [ruleFlatDatum.value],
    })
    .then((response) => {
      if (response.data.mark == "OK") {
        ElMessage.success("保存成功");
        // 更新原始数据
        ruleFlatDatumOrigin.value = JSON.parse(
          JSON.stringify(ruleFlatDatum.value)
        );
      } else {
        alert("保存失败：" + response.data.msg);
        console.error("saveAllChanges, 保存失败：", response.data);
      }
    })
    .catch((error) => {
      alert("保存失败：", error);
      console.error("saveAllChanges, 保存失败：", error);
    });
};

// 重置所有修改
const resetAllChanges = () => {
  if (ruleFlatDatumOrigin.value) {
    ruleFlatDatum.value = JSON.parse(JSON.stringify(ruleFlatDatumOrigin.value));
    ElMessage.info("已还原所有修改");
  } else {
    ElMessage.warning("没有可还原的数据");
  }
};

// ============ 定位功能 ============
// 导入 ruleLocate 组件
import RuleLocate from "./ruleLocate.vue";
// 定位查询事件
const isLocateDialogVisible = ref(false);
const ruleMenu = ref([]);
const locate = () => {
  // 调用后端 api/rule_flatten/list，用post，请求体为 reqBody
  axios
    .post("/api/rule_flatten/list", reqBody.value)
    .then((response) => {
      if (response.data.mark == "OK") {
        ruleMenu.value = response.data.data;
        isLocateDialogVisible.value = true; // 打开对话框
      } else {
        alert("定位查询失败：" + response.data.msg);
        console.error("locate, 定位查询失败：", response.data);
      }
    })
    .catch((error) => {
      alert("定位查询失败：", error);
      console.error("locate, 定位查询失败：", error);
    });
};

// 定位查询后的选择事件：直接查询该 rule_id
const handleLocateSelected = (selectedRuleId) => {
  reqBody.value.rule_id = selectedRuleId;
  reqBody.value.ruleId = selectedRuleId;
  isLocateDialogVisible.value = false; // 关闭对话框
  searchByRuleId(); // 直接查询
};

// ============ 日志功能 ============
// 导入 ruleLog 组件
import RuleLog from "./ruleLog.vue";
// 定义日志弹窗
const isLogDialogVisible = ref(false);

// 显示日志弹窗
const showLogDialog = () => {
  console.log("显示日志弹窗，当前数据:", ruleFlatDatum.value?.logList);
  isLogDialogVisible.value = true;
};

// 定义修改日志列表的事件处理函数
const handleUpdateLogList = (newLogList) => {
  console.log("父组件接收到日志更新:", newLogList);
  if (ruleFlatDatum.value) {
    // 只有在接收到新数据时才设置 logList
    ruleFlatDatum.value.logList = newLogList;
    console.log("已更新 ruleFlatDatum.logList:", ruleFlatDatum.value.logList);
  } else {
    console.warn("ruleFlatDatum.value 为 null，无法更新日志");
  }
};

// ============ JSON 编辑及功能 ============
// JSON 编辑器配置（其实没有什么用）
const editorOptions = {
  mode: "tree",
  modes: ["code", "form", "text", "tree", "view"],
  search: true,
  navigationBar: true, // 启用导航栏
  statusBar: true, // 启用状态栏
  mainMenuBar: true, // 启用主菜单栏
  readOnly: false,
  showArrayIndices: true, // 显示数组索引
  enableSort: true, // 启用排序
  enableTransform: true, // 启用变换
  indentation: 2, // 缩进
  theme: "ace/theme/jsoneditor", // 使用jsoneditor主题
};

// ============ 医院功能 ============
const hspAbbrList = ref([]);
// 获取医院列表，从后端 /api/rule_apply/list/hsp_abbr，用post
const getHspAbbrList = () => {
  axios
    .post("/api/rule_apply/list/hsp_abbr")
    .then((response) => {
      if (response.data.mark == "OK") {
        hspAbbrList.value = response.data.data;
      } else {
        alert("获取医院列表失败：" + response.data.msg);
        console.error("getHspAbbrList, 获取医院列表失败：", response.data);
      }
    })
    .catch((error) => {
      alert("获取医院列表失败：", error);
      console.error("getHspAbbrList, 获取医院列表失败：", error);
    });
};
// 初始化时获取医院列表
getHspAbbrList();
// 获得关注医院
const focusHsp = ref(null);
// 监听 hspAbbrList 的变化，设置 focusHsp 为第一个医院
watch(
  () => hspAbbrList.value,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      focusHsp.value = newVal[0];
    } else {
      focusHsp.value = null;
    }
  },
  { immediate: true } // 立即执行一次，以初始化 focusHsp
);

// ============ apply功能 ============
import RuleApply from "./ruleApply.vue";
const applyData = ref([]);
// 通过 ruleId 与 hspAbbr 获取 applyData，通过后端/api/rule_apply/query/by_rule_id，post
const getApplyData = () => {
  if (ruleFlatDatum.value?.ruleId && focusHsp.value) {
    axios
      .post("/api/rule_apply/query/by_rule_id", {
        ruleId: ruleFlatDatum.value.ruleId,
        hspAbbr: focusHsp.value,
      })
      .then((response) => {
        if (response.data.mark == "OK") {
          applyData.value = response.data.data;
        } else {
          alert("获取APPLY数据失败：" + response.data.msg);
          console.error("getApplyData, 获取APPLY数据失败：", response.data);
        }
      })
      .catch((error) => {
        alert("获取APPLY数据失败：", error);
        console.error("getApplyData, 获取APPLY数据失败：", error);
      });
  } else {
    applyData.value = [];
  }
};
// 监听 ruleFlatDatum.ruleId 与 focusHsp 的变化，获取 applyData
watch(
  () => [ruleFlatDatum.value?.ruleId, focusHsp.value],
  ([newRuleId, newHspAbbr]) => {
    if (newRuleId && newHspAbbr) {
      getApplyData();
    } else {
      applyData.value = [];
    }
  },
  { immediate: true }
);

// ============ sql功能 ============
import RuleSqlStr from "./ruleSqlStr.vue";
// 定义 sqlData 变量
const sqlData = ref([]);
// 通过 ruleId 获取 sqlData，通过后端/api/rule_apply/query_sql/by_rule_id
const getSqlData = () => {
  if (ruleFlatDatum.value?.ruleId) {
    axios
      .post("/api/rule_apply/query_sql/by_rule_id", {
        ruleId: ruleFlatDatum.value.ruleId,
        hspAbbr: focusHsp.value,
      })
      .then((response) => {
        if (response.data.mark == "OK") {
          sqlData.value = response.data.data;
        } else {
          alert("获取SQL数据失败：" + response.data.msg);
          console.error("getSqlData, 获取SQL数据失败：", response.data);
        }
      })
      .catch((error) => {
        alert("获取SQL数据失败：", error);
        console.error("getSqlData, 获取SQL数据失败：", error);
      });
  } else {
    sqlData.value = [];
  }
};
// 监听 ruleFlatDatum.ruleId 与 focusHsp 的变化，获取 sqlData
watch(
  () => [ruleFlatDatum.value?.ruleId, focusHsp.value],
  ([newRuleId, newHspAbbr]) => {
    if (newRuleId && newHspAbbr) {
      getSqlData();
    } else {
      sqlData.value = [];
    }
  },
  { immediate: true }
);

// 引入 ruleSql 组件
import RuleSql from "./ruleSql.vue";
</script>

<style>
.block {
  background-color: white; /* Set a background color */
  margin: 5px; /* Set a margin */
  padding: 10px;
}

/* 对表单中的元素进行修正 */
.form-item {
  margin-bottom: 5px; /* Corrected margin-bottom property */
}

.form-input-range {
  width: 120px;
}

.inline-form-btn {
  margin-left: 150px;
}

/* 拉长 el-select 选项框宽度 */
.el-select {
  min-width: 192px;
}

.form-item-numbers .el-input {
  width: 91px;
}

/* 对表格中的元素进行修正 */
.el-table td.el-table__cell {
  padding: 0px;
}
.el-table th.el-table__cell {
  padding: 0px;
  background-color: rgb(247, 249, 247);
}

.el-table .cell {
  padding: 3px;
  line-height: 17px;
}

.block2and3 {
  display: flex;
  width: 100%;
}

.block2 {
  width: 48%;
  height: 80vh;
}

.block3 {
  margin-left: 20px;
  width: 48%;
  height: 80vh;
}

.block3-btnbox {
  margin-bottom: 10px;
}
</style>
